package com.zy.qudadid.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zy.bean.Dingdan;
import com.zy.lcpassenger.R;
import com.zy.qudadid.model.ReportTitle;
import com.zy.qudadid.model.Stroke;
import com.zy.qudadid.model.StrokeInfor;
import com.zy.qudadid.network.Const;
import com.zy.qudadid.presenter.base.BasePresenterImp;
import com.zy.qudadid.ui.activity.base.ToolBarActivity;
import com.zy.qudadid.ui.widget.CustomImageView;
import com.zy.qudadid.ui.widget.FlowLayout;
import com.zy.qudadid.ui.widget.TagAdapter;
import com.zy.qudadid.ui.widget.TagFlowLayout;
import com.zy.qudadid.utils.AESCrypt;
import com.zy.qudadid.utils.StringUtil;
import com.zy.qudadid.utils.ToolsUtil;
import com.zy.util.JsonUtils;
import com.zy.util.UserUtil;
//import com.zhy.http.okhttp.OkHttpUtils;
//import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

public class PingJiaSiJiActivity extends ToolBarActivity {


    @Bind(R.id.imgHead)
    CustomImageView imgHead;
    @Bind(R.id.txtName)
    TextView txtName;
    @Bind(R.id.txtTip)
    TextView txtTip;
    @Bind(R.id.ll_tip)
    LinearLayout llTip;
    @Bind(R.id.txtCarNumber)
    TextView txtCarNumber;
    @Bind(R.id.imgStar)
    ImageView imgStar;
    @Bind(R.id.txtOrderNum)
    TextView txtOrderNum;
    @Bind(R.id.imgCall)
    ImageView imgCall;
    @Bind(R.id.txtPrice)
    TextView txtPrice;
    @Bind(R.id.os_star_rb)
    RatingBar osStarRb;
//    @Bind(R.id.tag_group)
//    TagGroup tagGroup;
    @Bind(R.id.txtPingJia)
    TextView txtPingJia;
    @Bind(R.id.main_rl)
    TagFlowLayout rl;

    StrokeInfor item;

    /**
     * 选择规格
     */
    List<String> dataList;

    @Override
    protected CharSequence provideTitle() {
        return "评价司机";
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.pingjiatitle;
    }

    @Override
    public void initListeners() {

    }

    private String ratingNum="5";

    ArrayList<ReportTitle> list = new ArrayList<>();
    String[] strTitle;

    private String phone="";
    private String order_id="";

    @Override
    protected void initThings(Bundle savedInstanceState) {
        super.initThings(savedInstanceState);

        item = (StrokeInfor) getIntent().getExtras().getSerializable("item");

        osStarRb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                ratingNum = rating+"";
            }
        });


        getDriverInfo();

        getTag();

    }

    private void getDriverInfo() {
        Map<String,String> map = new HashMap<>();
        map.put("user_id",new UserUtil(getContext()).getUserId());
        map.put("type","2");
        map.put("order_id",item.id);
        String json = JsonUtils.toJson(map);
        String data1 = null;
        try {
            data1 = AESCrypt.getInstance().encrypt(json);
            String d = StringUtil.replaceBlank(data1);
            OkHttpUtils.post()
                    .url(Const.BASE_URL+"api.php/Order/order_details")
                    .addParams("args",d)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int i) {
                            ToolsUtil.print("----","获取订单详情错误："+e.getMessage().toString());
                        }

                        @Override
                        public void onResponse(String response,int i) {
                            JSONObject json;
                            try {
                                json = new JSONObject(response);
                                int code = json.getInt("code");
                                if(code == 200){
                                    final JSONObject datas = json.getJSONObject("datas");
                                    String star = datas.getString("star");
                                    if(star.equals("0.0")){
                                        imgStar.setImageResource(R.drawable.star_0);
                                    }else if(star.equals("1.0")){
                                        imgStar.setImageResource(R.drawable.star_1);
                                    }else if(star.equals("2.0")){
                                        imgStar.setImageResource(R.drawable.star_2);
                                    }else if(star.equals("3.0")){
                                        imgStar.setImageResource(R.drawable.star_3);
                                    }else if(star.equals("4.0")){
                                        imgStar.setImageResource(R.drawable.star_4);
                                    }else if(star.equals("5.0")){
                                        imgStar.setImageResource(R.drawable.star_5);
                                    }else if(star.equals("1.5")){
                                        imgStar.setImageResource(R.drawable.star_2);
                                    }else if(star.equals("0.5")){
                                        imgStar.setImageResource(R.drawable.star_1);
                                    }else if(star.equals("2.5")){
                                        imgStar.setImageResource(R.drawable.star_3);
                                    }else if(star.equals("3.5")){
                                        imgStar.setImageResource(R.drawable.star_4);
                                    }else if(star.equals("4.5")){
                                        imgStar.setImageResource(R.drawable.star_5);
                                    }

                                    txtName.setText(datas.optString("driver_realname"));
                                    txtCarNumber.setText(datas.optString("carnumber"));
                                    txtOrderNum.setText(datas.getJSONObject("driver").optString("order_count"));

                                    Glide.with(getContext()).load(Const.BASE_IMG+datas.optString("avatar")).placeholder(R.drawable.adm).into(imgHead);

                                    phone = datas.optString("driver_mobile");
                                    order_id = datas.optString("id");

                                    txtPrice.setText(datas.optString("price"));
                                    if(Double.parseDouble(datas.optString("tip"))>0){
                                        llTip.setVisibility(View.VISIBLE);
                                        txtTip.setText(datas.optString("tip"));
                                    }else{
                                        llTip.setVisibility(View.GONE);
                                    }

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private int curPosition=-1;

    public void getTag(){
        Map<String,String> map = new HashMap<>();
        map.put("type","3");
        String json = JsonUtils.toJson(map);
        String data1 = null;
        try {
            data1 = AESCrypt.getInstance().encrypt(json);
            String d = StringUtil.replaceBlank(data1);
            OkHttpUtils.post()
                    .url(Const.BASE_URL+"api.php/Order/dictionaries_title")
                    .addParams("args",d)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call,Exception e,int i) {

                        }

                        @Override
                        public void onResponse(String response,int i) {
                            JSONObject json;
                            try {
                                json = new JSONObject(response);
                                int code = json.getInt("code");
                                if(code == 200){
                                    JSONArray datas = json.getJSONArray("datas");
                                    list = new Gson().fromJson(datas.toString(),new TypeToken<ArrayList<ReportTitle>>(){}.getType());

                                    final LayoutInflater mInflater = LayoutInflater.from(getContext());

                                    dataList = new ArrayList<String>();

                                    for (ReportTitle item :
                                            list) {
                                        dataList.add(item.getTitle());
                                    }

//                                    rl.setMaxSelectCount();
                                    rl.setAdapter(new TagAdapter<String>(dataList)
                                    {
                                        @Override
                                        public View getView(FlowLayout parent, int position, String s)
                                        {
                                            TextView tv = (TextView) mInflater.inflate(R.layout.tv,
                                                    rl, false);
                                            tv.setText(s);
                                            return tv;
                                        }
                                    });
                                    rl.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
                                    {
                                        @Override
                                        public boolean onTagClick(View view, int position, FlowLayout parent)
                                        {
                                            curPosition = position;
                                            TextView tv = (TextView) mInflater.inflate(R.layout.tv,
                                                    rl, false);
//                                            for(int i=0;i<dataList.size();i++){
//                                                if(position == i){
//                                                    tv.setTextColor(getResources().getColor(R.color.white));
////                                                    tv.setBackgroundResource(R.drawable.border_whiteback_greenstroke_4dp);
//                                                }else{
//                                                    tv.setTextColor(getResources().getColor(R.color.black));
////                                                    tv.setBackgroundResource(R.drawable.border_green_4dp);
//                                                }
//                                            }
                                            return true;
                                        }
                                    });


//                                    strTitle = new String[list.size()];
//                                    int i=0;
//                                    for (ReportTitle item :
//                                            list) {
//                                        strTitle[i] = item.getTitle();
//                                        i++;
//                                    }
//
//                                    tagGroup.setTags(strTitle);
//
//
//                                    tagGroup.setOnTagClickListener(new TagGroup.OnTagClickListener() {
//                                        @Override
//                                        public void onTagClick(String tag) {
//
//                                            toast("选中："+tag);
//                                        }
//                                    });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public BasePresenterImp createPresenter() {
        return null;
    }


    @OnClick({R.id.imgCall, R.id.txtPingJia})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgCall:
                Intent it = new Intent();
                it.setAction(Intent.ACTION_CALL);
                it.setData(Uri.parse("tel:"+phone));
                startActivity(it);
                break;
            case R.id.txtPingJia:
                String str="";
                if(rl.getSelectedList().size()>0) {
                    Iterator i = rl.getSelectedList().iterator();//先迭代出来
                    while (i.hasNext()) {//遍历

                        str += dataList.get(Integer.parseInt(i.next().toString())).toString() + ",";
                    }
//                String[] str1 = (String[]) rl.getSelectedList().toArray();
//                for (int i=0;i<str1.length;i++){
//                    str+=str1[i]+",";
//                }
                    str = str.substring(0, str.length() - 1);

                    Map<String,String> map = new HashMap<>();
                    map.put("user_id",new UserUtil(getContext()).getUserId());
                    map.put("title",str);
                    map.put("star",ratingNum);
                    map.put("order_id",order_id);
                    String json = JsonUtils.toJson(map);
                    String data1 = null;
                    try {
                        data1 = AESCrypt.getInstance().encrypt(json);
                        String d = StringUtil.replaceBlank(data1);
                        OkHttpUtils.post()
                                .url(Const.BASE_URL+"api.php/Order/comment")
                                .addParams("args",d)
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call,Exception e,int i) {

                                    }

                                    @Override
                                    public void onResponse(String response,int i) {
                                        JSONObject json;
                                        try {
                                            json = new JSONObject(response);
                                            int code = json.getInt("code");
                                            if(code == 200){
                                                toast("评价成功");
                                                finish();
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }else{
                    toast("请选择评价");
                }


                break;
        }
    }
}
